/**
 * Copyright (c) 2012 Axa Holding Belgium, SA. All rights reserved.
 * This software is the confidential and proprietary information of the AXA Group.
 */
package chabernac.android.wordbattle.db;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class AsyncDatabaseLoaderDecorator implements iDatabaseLoader {
  
  private final iDatabaseLoader myDataBaseLoader;
  private final ExecutorService myExecutorService = Executors.newSingleThreadExecutor();
  private final Map<String, CountDownLatch> myLanguageLoaderLatches = new ConcurrentHashMap<String, CountDownLatch>();
  
  public AsyncDatabaseLoaderDecorator( iDatabaseLoader aDatabaseLoader ) {
    super();
    myDataBaseLoader = aDatabaseLoader;
  }

  public boolean isLanguageLoaded( String aLanguage ) {
    return myDataBaseLoader.isLanguageLoaded( aLanguage );
  }

  public void waitForLanguage( String aLanguage ) throws InterruptedException {
    if(!myLanguageLoaderLatches.containsKey( aLanguage )) return;
    CountDownLatch theLanguageLatch = myLanguageLoaderLatches.get(aLanguage);
    if(theLanguageLatch != null){
      theLanguageLatch.await();
    }
  }

  public void loadLanguage( final String aLanguage ) {
    //we are already loading this language
    if(myLanguageLoaderLatches.containsKey( aLanguage )) return;

    final CountDownLatch theLanguageLatch = new CountDownLatch( 1 );
    myLanguageLoaderLatches.put( aLanguage, theLanguageLatch );
    myExecutorService.execute( new Runnable(){
      public void run(){
        try{
          myDataBaseLoader.loadLanguage( aLanguage );
        }finally{
          theLanguageLatch.countDown();
          myLanguageLoaderLatches.remove( aLanguage );
        }
      }
    });
  }
}
